<?php
namespace app\api\controller;

use app\common\lib\CryptoJsAes;
use app\common\model\SmsCodeModel;
use app\common\model\UserModel;
use app\middleware\Auth;

/**
 * 登录控制器
 * @author 贺强
 * @time   2021-10-21 10:10:55
 */
class Login extends Common
{
    protected $middleware = [Auth::class];

    /**
     * 用户登录
     * @author 贺强
     * @time   2021-10-21 10:33:57
     */
    public function index()
    {
        $param = $this->param;
        if (empty($param['code']) && empty($param['password']) || empty($param['mobile'])) {
            return ajax('参数缺失', 301);
        }
        $ok = 0;
        if (!empty($param['code'])) {
            $time = SmsCodeModel::getFieldValue('ctime', ['mobile' => $param['mobile'], 'code' => $param['code']], ['ctime' => 'desc']);
            SmsCodeModel::delByWhere(['mobile' => $param['mobile']]);
            if (empty($time)) {
                return ajax('无效验证码', 302);
            }
            $time += env('app.code_validity', 600);
            if ($time < time()) {
                return ajax('验证码过期', 303);
            }
            $ok = 1;
        }
        if (!empty($param['password'])) {
            $salt = env('app.aes_salt', '258369471xcvn019');
            $iv = env('app.aes_iv', 'y9shd1pdrwvapq8b');
            $pwd1 = CryptoJsAes::decryptT($param['password'], $salt, $iv);
            $param['password'] = $pwd1;
        }
        $type = 1; // 1:登录  2:注册
        $user = UserModel::getModel(['mobile|username' => $param['mobile']], ['id', 'username', 'mobile', 'name', 'nickname', 'avatar', 'password', 'login_count', 'status'], '', false);
        if (empty($user)) {
            if (!$ok || !preg_match('/^1[3|4|5|6|7|8|9]\d{9}$/', $param['mobile'])) {
                return ajax('账号或密码错误', 401);
            }
            $data = ['username' => $param['mobile'], 'mobile' => $param['mobile'], 'status' => 1, 'name' => '', 'gender' => 0, 'login_time' => time(), 'login_ip' => '', 'login_count' => 0, 'age' => 0, 'mtime' => 0];
            if (!empty($param['password'])) {
                $data['password'] = get_md5_password($param['password']);
            } else {
                $data['password'] = '';
            }
            $id = UserModel::add($data);
            $user = UserModel::getModel(['id' => $id]);
            $type = 2;
        } elseif (empty($param['code'])) {
            $pwd = get_md5_password($param['password']);
            // 如果验证码为空则是密码登录
            if (!password_verify($param['password'], $user['password']) && $pwd !== $user['password']) {
                return ajax('用户名或密码错误', 304);
            }
        }
        if (intval($user['status']) === 0) {
            return ajax('账号还未审核', 101);
        }
        if (intval($user['status']) === 4) {
            return ajax('账号被禁用', 102);
        }
        unset($user['password']);
        // 赋值登录时间和登录IP
        $user['login_time'] = time();
        $user['login_ip'] = $this->request->ip();
        if (empty($user['login_count'])) {
            $user['login_count'] = 0;
        }
        $user['login_count'] += 1;
        event('UserLogin', $user); // 登录成功后记录登录时间和IP
        $user['nonce'] = get_random_str();
        if (!empty($user['avatar']) && preg_match('/^uploads*/', $user['avatar'])) {
            $user['avatar'] = str_replace('\\', '/', $user['avatar']);
            $user['avatar_url'] = config('app.params.website.img') . $user['avatar'];
        } else {
            $user['avatar_url'] = '';
        }
        // 生成登录 token
        $token = Common::dataEncrypt($user);
        return ajax('登录成功', 200, ['token' => $token, 'userinfo' => $user, 'type' => $type]);
    }

    /**
     * 用户注册
     * @author 贺强
     * @time   2021-10-21 10:39:10
     */
    public function register()
    {
        $param = $this->param;
        if (empty($param['mobile']) || empty($param['code'])) {
            return ajax('参数缺失', 301);
        }
        $mobile = $param['mobile'];
        $time = SmsCodeModel::getFieldValue('ctime', ['mobile' => $mobile, 'code' => $param['code']]);
        if (empty($time)) {
            return ajax('无效验证码', 302);
        }
        $time += env('app.code_validity', 600);
        if ($time < time()) {
            return ajax('验证码过期', 303);
        }
        $data = ['username' => $mobile, 'mobile' => $mobile, 'status' => 1, 'name' => '', 'gender' => 0, 'login_time' => time(), 'login_ip' => '', 'age' => 0, 'mtime' => 0];
        $id = UserModel::add($data);
        $data = ['id' => $id, 'mobile' => $mobile, 'username' => $mobile, 'login_time' => time(), 'login_ip' => $this->request->ip()];
        event('UserLogin', $data);
        $data['nonce'] = get_random_str();
        SmsCodeModel::delByWhere(['mobile' => $mobile]);
        $token = Common::dataEncrypt($data); // 生成 token
        return ajax('注册成功', 200, ['token' => $token]);
    }
}
